package com.videomeetting.legend.videomeetting.activity.fragment;

import android.Manifest;
import android.content.ContentResolver;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.Toast;

import com.videomeetting.legend.videomeetting.R;
import com.videomeetting.legend.videomeetting.activity.adapater.FileChooseAdapater;
import com.videomeetting.legend.videomeetting.activity.bean.MessageEvent;
import com.videomeetting.legend.videomeetting.activity.bean.VideoBean;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by legend on 18-6-29.
 */

public class VoiceFragment extends Fragment {
    private EditText editText;
    private List<VideoBean> videoBeans;
    SharedPreferences sharedPreferences;
    SeekBar inputVolume;
    SeekBar outputVolume;
    SeekBar backgroundVolume;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);


    }
//    private String backgroundBackUrl="";
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(MessageEvent messageEvent) {
        if (messageEvent.getCode() == 2) {
            Toast.makeText(getActivity(), messageEvent.getMessage(), Toast.LENGTH_SHORT);
            editText.setText(messageEvent.getMessage());
        }
//        if (messageEvent.getCode() == 12) {
//            backgroundBackUrl = messageEvent.getMessage();
////            Toast.makeText(getActivity(), messageEvent.getMessage(), Toast.LENGTH_SHORT);
////            editText.setText(messageEvent.getMessage());
//        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 123);
                } else {
                    //内部储存
                    videoBeans = queryVoice();//getStorageDirectory
                }
            }
        }).start();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 123:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    videoBeans = queryVoice();
//                    localVideos = getFileName(new File("/storage").listFiles());
                } else {
                    Toast.makeText(getActivity(), "You denied the permission", Toast.LENGTH_SHORT).show();
                }
        }
    }

    private List<VideoBean> queryVoice() {
        videoBeans = new ArrayList<>();
        ContentResolver resolver = getActivity().getContentResolver();
        Cursor cursor = resolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                null, null, null, MediaStore.Audio.Media.DEFAULT_SORT_ORDER);
        Log.i("legend", "onCreate: " + cursor);
        Log.i("legend", "onCreate: getCount" + cursor.getCount());
        Log.i("legend", "onCreate: getColumnCount" + cursor.getColumnCount());
        if (cursor != null) {
            while (cursor.moveToNext()) {
                VideoBean bean = new VideoBean();
                String tilte = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME));
                float duration = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DURATION)) / (60000);
                float size = (float) cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.SIZE)) / (1024 * 1024);
                int column_index = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
                String path = cursor.getString(column_index);
                Log.i("legend", "onCreate: tilte" + tilte);
                Log.i("legend", "onCreate: duration" + duration);
                Log.i("legend", "onCreate: size" + size);
                bean.setName(tilte);
                bean.setTime(String.valueOf(duration));
                bean.setLenght(String.valueOf(size));
                bean.setFileCreateTime("2018-07-11");
                bean.setFilePath(path);
                videoBeans.add(bean);
            }
            cursor.close();
        }
        return videoBeans;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        EventBus.getDefault().register(this);
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_voice, container, false);
        sharedPreferences = getActivity().getSharedPreferences("voice", Context.MODE_PRIVATE);
        editText = (EditText) view.findViewById(R.id.fragment_voice_local);
        Button fileChoose = (Button) view.findViewById(R.id.fragment_voice_file_choose);
        Button saveBtn = (Button) view.findViewById(R.id.fragment_voice_save_btn);
        int input = sharedPreferences.getInt("input", 0);
        int output = sharedPreferences.getInt("output", 0);
        int background = sharedPreferences.getInt("background", 0);
        String backgroundUrl = sharedPreferences.getString("backgroudUrl", "");
        inputVolume = (SeekBar) view.findViewById(R.id.fragment_voice_input_volume_seekbar);
//        outputVolume = (SeekBar) view.findViewById(R.id.fragment_voice_output_volume_seekbar);
//        backgroundVolume = (SeekBar) view.findViewById(R.id.fragment_voice_background_volume_seekbar);
        if (input > 0) {
            inputVolume.setProgress(input);
        }
//        if (output > 0) {
//            outputVolume.setProgress(output);
//        }
//        if (background > 0) {
//            backgroundVolume.setProgress(background);
//        }
        if (!TextUtils.isEmpty(backgroundUrl)){
            editText.setText(backgroundUrl);
        }else {
            editText.setText("usb\\date\\0\\music");
        }
        fileChoose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FileChooseFragment speedTestFragment = new FileChooseFragment();
                FileChooseAdapater adapater = new FileChooseAdapater(getActivity(), videoBeans);
                speedTestFragment.setAdapater(adapater);
                speedTestFragment.show(getChildFragmentManager(), "voicechoose");
            }
        });
        saveBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SharedPreferences.Editor edit = sharedPreferences.edit();
                edit.putInt("input", inputVolume.getProgress());
                edit.putInt("output", outputVolume.getProgress());
                edit.putInt("background", backgroundVolume.getProgress());
                edit.putString("backgroudUrl", editText.getText().toString().trim());
                edit.commit();
            }
        });

        return view;
    }
}
